package com.nxu.comtrol;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.nxu.service.DoctorService;
import com.nxu.service.impl.DoctorServiceImpl;

/**
 * Servlet implementation class DoctorRegister
 */
@WebServlet("/doctorRegister")
public class DoctorRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoctorRegister() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

  
}	
		
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf8");
	    String Dname = request.getParameter("dname");
		String Dpassword= request.getParameter("dpassword"); 
		
		HttpSession session=request.getSession();

		// 获取当前会话的密码错误次数和最后一次错误时间戳
		Integer loginAttempts = (Integer) session.getAttribute("loginAttempts");
		Long lastFailedLoginTimestamp = (Long) session.getAttribute("lastFailedLoginTimestamp");

		// 如果密码错误次数为空，则初始化为0
		if (loginAttempts == null) {
			loginAttempts = 0;
		}

		// 如果最后一次错误时间戳不为空且距离当前时间少于5分钟，则判断为锁定状态
		boolean isLocked = (lastFailedLoginTimestamp != null) && (new Date().getTime() - lastFailedLoginTimestamp) < 5 * 60 * 1000;

		// 判断是否为锁定状态
		if (isLocked) {
			// 显示锁定信息
			session.setAttribute("lockMsg","密码错误次数过多，请稍后再试！请5分钟后在试试");
			response.sendRedirect("jsp/doctorRegister.jsp");
			return;
		}
		session.setAttribute("dname",Dname);
		
		DoctorService doctorservice= new DoctorServiceImpl();
		String password = doctorservice.selectDoctor(Dname);
		
		if(Dpassword.equals(password)) {
			//登录成功清除
			session.removeAttribute("lockMsg");
			session.removeAttribute("loginAttempts");
			session.removeAttribute("lastFailedLoginTimestamp");
			request.getRequestDispatcher("/selectShowDoctor").forward(request, response);
		}else {
			//登录错误增加错误次数记录逻辑
			//增加全局sesseion保存，记录当前错误次数，如果错误超过3次，锁定5分钟
			// 密码错误，更新密码错误次数和最后一次错误时间戳
			loginAttempts++;
			session.setAttribute("loginAttempts", loginAttempts);
			session.setAttribute("lastFailedLoginTimestamp", new Date().getTime());

			// 判断密码错误次数是否达到三次
			if (loginAttempts >= 3) {
				isLocked = true;
				session.setAttribute("isLocked", isLocked);
			}
			response.sendRedirect("jsp/doctorRegister.jsp");
		}
	}	
	
}